package com.markerhub.service.impl;

import com.alibaba.fastjson.JSON;
import com.markerhub.common.RedisKey;
import com.markerhub.common.lang.Result;
import com.markerhub.handler.Tb_UserThreadLocal;
import com.markerhub.mapper.Tb_UserMapper;
import com.markerhub.pojo.dto.Tb_UserDto;
import com.markerhub.service.Tb_userService;
import com.markerhub.util.JWTUtils;
import com.markerhub.util.RedisUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author by MaXiaofeng
 * @Description 后台管理员接口类
 * @Date 2022/2/22 19:33
 * @Version 1.0.0
 */
@Service
public class Tb_userServiceImpl implements Tb_userService {
    @Resource
    private Tb_UserMapper tb_userMapper;

    @Override
    public Result login(String username, String password) {
        String pass = tb_userMapper.selectPasswordByUsername(username);
        String unDecodePass = RedisKey.USER_LOGIN + "_" + password;
        if (pass == null) {
            return Result.fail("该账号不存在,请确认");
        }
        if (!pass.equals(DigestUtils.md5DigestAsHex(unDecodePass.getBytes()))) {
            return Result.fail("账号或密码错误，请重试");
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("username", username);
        int userId = tb_userMapper.findUserIdByUsername(username);
        resultMap.put("userId", userId);
        String token = JWTUtils.sign((long) userId);
        //从redis中取出token对应的账号信息
        String userJson = RedisUtil.StringOps.get(RedisKey.TOKEN + token);
        if (userJson != null) {
            /**
             * 如果redis中存在token
             * 1、解析token中的用户信息
             * 2、将用户信息放入线程变量
             */
            Tb_UserDto userDto = JSON.parseObject(userJson, Tb_UserDto.class);
            //得到了用户信息放入ThreadLocal当中
            Tb_UserThreadLocal.remove();
            Tb_UserThreadLocal.put(userDto);
        } else {
            /**
             * 如果redis中不存在该用户的token或该token失效
             * 1、重新赋值userDto
             * 2、将userDto解析为json存入redis中
             */
            Tb_UserDto userDto = new Tb_UserDto();
            userDto.setUsername(username);
            userDto.setId(userId);
            userDto.setToken(token);
            RedisUtil.StringOps.setEx(RedisKey.TOKEN + token, JSON.toJSONString(userDto), 8, TimeUnit.HOURS);
            resultMap.put("token", token);
        }
        return Result.success("后台管理员登陆成功", resultMap);
    }

    @Override
    public Result updateUser(int userId, String username, String password) {
        String unDecodePass = RedisKey.USER_LOGIN + "_" + password;
        String newPassword = DigestUtils.md5DigestAsHex(unDecodePass.getBytes());
        if (tb_userMapper.updatePasswordByUserId(userId, username, newPassword) >= 1) {
            return Result.success("更新密码成功");
        }
        return Result.fail("更新密码失败");
    }
}
